// 引入axios
import axios from 'axios';
import store from '../store/index'
import qs from 'qs'

let BASE_URL = "http://127.0.0.1:8110"

// 创建axios实例
const httpService = axios.create({
    // url前缀-'http:xxx.xxx'
    baseURL: BASE_URL, // 需自定义
    // 请求超时时间
    timeout: 30000 // 需自定义
});

httpService.interceptors.request.use(
    config => {
        config.headers['Authorized'] = `${sessionStorage.getItem('token')}`
        return config;
    },
    error => Promise.error(error)
)

httpService.interceptors.response.use(
    response => {
        let res = response.data;
        if (res.code === 200) {
            return res.data;
        } else if (res.code === 300) {
            window.location.href = "http://" + location.hostname + ":8110/view/login.html"
        } else {
            return Promise.reject({
                code: res.code,
                message: res.message
            });
        }
    },
    error => {
        return Promise.reject(error);
    }
)

/**
 * GET请求
 * @param url 请求URL
 * @param params 请求参数
 * @returns {Promise<unknown>}
 */
function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/**
 *  post请求
 *  url:请求地址
 *  params:参数
 */
function postJson(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            headers: {
                "Content-Type": 'application/json; charset=utf8'
            },
            data: JSON.stringify(params)
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

function postForm(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded; charset=utf8"
            },
            data: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}


/**
 *  文件上传
 *  url:请求地址
 *  params:参数
 */
function fileUpload(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            headers: {'Content-Type': 'multipart/form-data'}
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export default {get, postForm, postJson}
